<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {

	function __construct(){
        parent::__construct();
        self::is_login();
    }

    function arrays($key = ''){
    	$data = array(
    		'cardType'=>array(
    			'1'=>'身份证',
				/*'2'=>'军官证',
				'3'=>'台胞证',
				'4'=>'护照',
				'5'=>'营业执照',*/
    		),
    		'sex' => array(
    			'0'=>'','1'=>'男','2'=>'女'
    		),
    		'statusArr' => array(
    			'0' => "<span>未申请</span>",
				'1' => "<span style='color:green;'>已通过</span>",
				'2' => "<span style='color:red;'>待审核</span>"
    		),
    	);
    	if ($key!='' && isset($data[$key])){
    		return $data[$key];
    	}else{
    		return $data;
    	}
    }

	function is_login(){
		$user = $this->session->userdata('zjy_user');
		//判断session是否存在
		if(isset($user['user_id']) && $user['user_id'] > 0){
			return $user;
		}else{//根据cookie判断用户是否选择保存登陆状态
			//cookie  key: zjy_online   pwd: zjy_login_20130826
			$ck_str = isset($_COOKIE["zjy_online"]) ? $_COOKIE["zjy_online"] : '';
			if($ck_str){
				$this->load->library('func');
				$tmp_u_str = $this->func->authcode($ck_str,'DECODE','zjy_login');
				$tmp_u_arr = explode(',',$tmp_u_str);
				if(count($tmp_u_arr) == 5){
					//$tmp_u_str: user_id,username,email,type_id,fstatus
					$tmp_u_id = $tmp_u_arr[0];
					$u_ret = self::get_by_uid($tmp_u_id);
					if($u_ret){
						if($u_ret['username']==$tmp_u_arr[1] && $u_ret['email']==$tmp_u_arr[2] && $u_ret['type_id']==$tmp_u_arr[3] && $u_ret['fstatus']==$tmp_u_arr[4]){
							$user = array(
								'user_id'  => $tmp_u_arr[0],
								'username' => $tmp_u_arr[1],
								'email'    => $tmp_u_arr[2],
								'type_id'  => $tmp_u_arr[3],
								'fstatus'  => $tmp_u_arr[4],
								'login_time' => time(),
							);
							//$user['login_time'] = time();
							//匹配自动登陆
							$this->session->set_userdata('zjy_user',$user);
							return $user;
						}else{
							return false;
						}
					}else{
						return false;
					}
				}else{
					return false;
				}
			}else{
				return false;
			}
		}
	}


	/**
	 * 检测用户名是否存在
	 * @param string $username 用户名
	 * @return int 查询结果的行数
	 */
	function check_username($username = ''){
		$this->db->select('user_id');
		$this->db->where('username', $username);
		$query = $this->db->get('zjy_user');
		//$this->db->select('user_id')->from('user')->where('username', $username)->limit(1, 0);
		return $query->num_rows();
	}

	/**
	 * 检测邮箱是否存在
	 * @param string $email 邮箱
	 * @return int 查询结果的行数
	 */
	function check_email($email = ''){
		$this->db->select('user_id');
		$this->db->where('email', $email);
		$query = $this->db->get('zjy_user');
		return $query->num_rows();
	}


	function get_username_by_id($user_id = ''){
		$user_id = intval($user_id);
		if($user_id < 1){
			return false;
		}

		$this->db->select('user_id,username');
		$this->db->where('user_id', $user_id);
		$query = $this->db->get('zjy_user');
		return $query->row_array();
	}

	function get_all_by_id($user_id = ''){
		$user_id = intval($user_id);
		if($user_id < 1){
			return false;
		}
		$this->db->where('user_id', $user_id);
		$query = $this->db->get('zjy_user');
		return $query->row_array();
	}


	/**
	 * 根据用户名获取用户ID 缓存
	 * @param $username
	 */
	function get_userid_by_username($username = ''){
		if($username == ''){
			return 0;
		}
		$this->db->select('user_id');
		$this->db->where('username', $username);
		$query = $this->db->get('zjy_user');
		$user_ret = $query->row_array();
		if(count($user_ret) == 0){
			return 0;
		}
		return $user_ret['user_id'];
	}


	/**
	 * 根据用户名获取用户对象
	 * @param $username
	 */
	function get_user_by_username($username = ''){
		if($username == ''){
			return 0;
		}
		$this->db->select('user_id,invite_userid');
		$this->db->where('username', $username);
		$query = $this->db->get('zjy_user');
		return $query->row_array();
	}

	/**
	 * 登陆验证
	 * @param string $phone 电话号码
	 * @param string $password 密码
	 * @return array/false
	 */
	function check_login($phone = '', $password = ''){
		$password = md5(md5($password));
		$sql = "select user_id,username,email,type_id,fstatus from zjy_user where (phone='{$phone}') and password='{$password}' limit 1";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			return $query->row_array();
		}else{
			return false;
		}
	}

	/**
	 * 后台登陆验证
	 * @param string $user 用户名/Email
	 * @param string $password 密码
	 * @return array/false
	 */
	function admin_check_login($user = '', $password = '', $smscode = ''){
		$password = md5(md5($password));
		$ctime = time()-24*60*60;
		$sql = "select user_id,username,email,type_id,fstatus from zjy_user where
				(username='{$user}' or email='{$user}') and password='{$password}'
				and smscode='{$smscode}' and smstime>{$ctime} limit 1";
		/*
		$sql = "select user_id,username,email,type_id,fstatus from zjy_user where
				(username='{$user}' or email='{$user}') and password='{$password}'
				limit 1";
		*/
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			return $query->row_array();
		}else{
			return false;
		}
	}

	/**
	 * 获取登录密码输错次数
	 * @param string $phone 用户名/Email
	 */
	function check_login_errnum($phone = ''){
		$sql = "select error_num from zjy_user where phone='{$phone}' limit 1";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			return $query->row_array();
		}else{
			return false;
		}
	}

	/**
	 * 密码输入错误次数+1
	 * @param $phone 用户名/Email/phone
	 */
	function set_error_num($phone = ''){
		$sql = "update zjy_user set error_num=error_num+1 where phone='{$phone}'";
		$query = $this->db->query($sql);
		return $this->db->affected_rows();
	}

	/**
	 * 登陆支付密码
	 * @param string $user 用户名/Email
	 * @param string $password 密码
	 * @return array/false
	 */
	function check_paypassword($user_id = '', $paypassword = ''){
		$paypassword = md5(md5($paypassword));
		$sql = "select count(*) as count from zjy_user where user_id=$user_id and paypassword='{$paypassword}' limit 1";
		$query = $this->db->query($sql);
		$result = $query->row_array();
		return $result['count'];
	}


	function user_attestation_status($parms=array(),$per_page=0,$page_size=10){
		$tmp = array();
		foreach($parms as $key => $val){
			if($val){
				if($key == 'username' || $key == 'realname'){
					$tmp[] = "`{$key}` like '%{$val}%'";
				}else{
					$tmp[] = "`{$key}` = '{$val}'";
				}
			}
		}
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);

		$sql = "SELECT p1.user_id,p1.username,p1.realname,p1.real_status,p1.email_status,p1.phone_status,p1.scene_status,p2.vip_status,p2.kefu_userid,p2.vip_verify_time,p1.add_time
FROM zjy_user AS p1
LEFT JOIN zjy_user_vip AS p2 ON p1.user_id=p2.user_id {$where} ORDER BY p1.user_id DESC LIMIT {$per_page},{$page_size};";
		$query = $this->db->query($sql);
		$data['list'] = $query->result_array();
		$sql = "SELECT COUNT(p1.user_id) AS count FROM zjy_user AS p1 LEFT JOIN zjy_user_vip AS p2 ON p1.user_id=p2.user_id {$where}";
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;
	}


	function user_attestation_info($user_id = 0){
		$sql = "SELECT p1.user_id,p1.username,p1.logintime,p1.add_time,p1.lasttime,
p1.realname,p1.sex,p1.card_type,p1.card_id,p1.card_pic1,p1.card_pic2,
p1.province,p1.city,p1.area,p1.nation,p1.real_status,p1.email,p1.email_status,
p1.video_status,p1.scene_status,p1.phone,p1.phone_status,p1.birthday,
p2.vip_status,p2.vip_verify_remark,p2.kefu_userid,
p3.marry,p3.child,p3.education_record,p3.house,p3.car,
p3.company_name,p3.company_type,p3.company_industry,p3.company_office,
p3.company_employee,p3.company_tel,p3.company_address,p3.company_weburl,
p3.linkman1,p3.relation1,p3.phone1,p3.linkman2,p3.relation2,p3.phone2, p3.fanwei, p3.nianjian, p3.qiye_background,
p3.qiye_type, p3.qiye_name, p3.qiye_employee, p3.zhuce, p3.income
FROM zjy_user AS p1
LEFT JOIN zjy_user_vip AS p2 ON p1.user_id=p2.user_id
LEFT JOIN zjy_user_info AS p3 ON p1.user_id=p3.user_id
WHERE p1.user_id = '{$user_id}' LIMIT 1";
		$query = $this->db->query($sql);
		return $query->row_array();
	}

	function real_status_list($parms=array(),$per_page=0,$page_size=10){
		$sql = "select user_id,username,realname,sex,nation,birthday,card_type,card_id,province,city,area,card_pic1,card_pic2,real_status from zjy_user";
		$tmp = array();
		foreach($parms as $key => $val){
			if($val){
				if($key == 'username' || $key == 'realname'){
					$tmp[] = "`{$key}` like '%{$val}%'";
				}else{
					$tmp[] = "`{$key}` = '{$val}'";
				}
			}
		}
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$sql .= $where;
		$order = " order by real_status desc,user_id desc";
		$sql .= $order;
		$sql .= " limit {$per_page},$page_size";
		$query = $this->db->query($sql);
		$data['list'] = $query->result_array();
		$sql = "select count(user_id) as count from zjy_user".$where;
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;
	}
	
	function real_status_count($where = null) {
		if(!empty($where)) 
			$_where = ' where real_status ='.$where;
		$sql = "select count(user_id) as count from zjy_user".$_where;
		$query = $this->db->query($sql);
		return $query->row()->count;
	}


	/***改版*************************************************************************************************/

	/**
	 * 添加用户
	 * @param array $data
	 * @return int $user_id
	 */
	function add($data = array()){
		$this->db->insert('zjy_user', $data);
		return $this->db->insert_id();
	}

	function get_by_uid($user_id){
		$key = 'zjy_user_' . $user_id;
		$this->mycache->delete($key);//@todo
		$row = $this->mycache->get_array($key);
		if($row == false){
			$this->db->where('user_id',$user_id);
			$query = $this->db->get('zjy_user');
			$row = $query->row_array();
			if($row){
				$this->mycache->set_array($key,$row);
			}
		}
		return $row;
	}

	/**
	 * 获取单条记录
	 */
	function get_one($where = array(),$select='*'){
		$this->db->select($select);
		if($where){
			$this->db->where($where);
		}
		$this->db->limit(1);
		$query = $this->db->get('zjy_user');
		return $query->row_array();
	}

	/**
	 * 获取列表记录
	 */
	public function get_list($where = array(),$select = '*')
	{
		$this->db->select($select);
        if($where != ''){
            $this->db->where($where);
        }
        $query = $this->db->get('zjy_user');
        $lists = $query->result_array();

        //获取推荐人的名字
        $userlist = array();
        foreach($lists as $list) {
            $row = $this->get_by_uid($list['invite_userid']);
            $list['invite_username'] = $row['username'];
            $userlist[] = $list;
        }

        return $userlist;
	}

	/**
	 * 修改用户信息
	 * @param array $data
	 * @return 影响行数/false
	 */
	function update($data = array(), $where = array()){
		$this->db->where($where);
		$this->db->update('zjy_user', $data);
		$res = $this->db->affected_rows();
		if($res > 0 && isset($where['user_id'])){
			$key = 'zjy_user_'.$where['user_id'];
			$this->mycache->delete($key);
		}
		return $res;
	}

	/**
	 * 分页列表 for admin
	 */
	function get_user_list($parms=array(),$per_page=0,$page_size=10){
		$tmp = array();
		foreach($parms as $key => $val){
			if($val){
				if($key == 'username' || $key == 'realname'){
					$tmp[] = "`{$key}` like '%{$val}%'";
				}elseif ($key=='is_admin'){
					$tmp[] = "`type_id` != '2'";
				}elseif($key=='add_time'){
					$user_start = strtotime($val.' 00:00:00');
					$user_end = strtotime($val.' 23:59:59');
					$tmp[] = "`{$key}` >= '{$user_start}'";
					$tmp[] = "`{$key}` <= '{$user_end}'";
				}else{
					$tmp[] = "`{$key}` = '{$val}'";
				}
			}
		}

		$select = "user_id,username,email,realname,phone,qq,sex,province,city,area,add_time";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$order = "order by user_id desc";
		$limit = " limit {$per_page},{$page_size}";
		$sql = "select {$select} from zjy_user {$where} {$order} {$limit}";
		$query = $this->db->query($sql);
		$data['user_list'] = $query->result_array();
		$sql = "select count(user_id) as count from zjy_user {$where}";
		$query = $this->db->query($sql);
		$data['user_count'] = $query->row()->count;
		return $data;
	}

	function get_name_list(){
		$key = 'zjy_name_list';
		$list = $this->mycache->get_array($key);
		if(!$list){
			$this->db->select('user_id,username');
			$query = $this->db->get('zjy_user');
			$result = $query->result_array();
			$list = array();
			if($result){
				foreach($result as $v){
					$list[$v['user_id']] = $v['username'];
				}
				$this->mycache->set_array($key,$list);
			}
		}
		return $list;
	}

	/**
	 * 客服列表
	 */
	function get_kefu_list(){
		$key = 'zjy_kefu_list';
		$this->mycache->delete($key);
		$tmpList = $this->mycache->get_array($key);

		if($tmpList == false){
			$sql = "SELECT p1.user_id,p1.username,p1.realname,p1.email,p1.phone,p1.sex,p1.qq,p2.tel,p2.user_desc
FROM zjy_user AS p1 LEFT JOIN zjy_user_info AS p2 ON p1.user_id=p2.user_id WHERE p1.type_id=3 AND p1.fstatus=1";
			$query = $this->db->query($sql);
			$result = $query->result_array();

			$list = array();
			if($result){
				foreach($result as $v){
					$list[$v['user_id']] = $v;
				}
			}
			//排序写死
			$tmpList = $list;
			$this->mycache->set_array($key,$tmpList);
		}
		return $tmpList;
	}

	/**
	 * 新总注册人数统计
	 */
	function reg_num(){
		$key = 'zjy_reg_num_'.date('Ymd');
		$ret = $this->mycache->get_array($key);
		if (!$ret){
			$ret = array();
			$today = strtotime(date('Y-m-d'));
			$yestoday = $today - 3600*24;
			$sql = "select count(user_id) as num from zjy_user";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$ret['total'] = $row['num']  * 7;
			$sql = "select count(user_id) as num from zjy_user where add_time>={$yestoday} and add_time<{$today}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$ret['new'] = $row['num'] * 7;
			$this->mycache->set_array($key,$ret,3600*24);
		}
		return $ret;
	}

	/**
	 * 添加登录日志
	 * @param $data
	 */
	function add_user_login_log($data = array()){
		$this->db->insert('zjy_user_login', $data);
		return $this->db->insert_id();
	}


	function del($id){
		return false;
	}

	function vip_status_list($parms=array(),$per_page=0,$page_size=10){
		$tmp = array();
		foreach($parms as $key => $val){
			if($val){
				if($key == 'username' || $key == 'realname'){
					$tmp[] = "`{$key}` like '%{$val}%'";
				}else{
					$tmp[] = "`{$key}` = '{$val}'";
				}
			}
		}
		$sql ="select v.user_id,u.username,v.kefu_userid,v.vip_status,v.vip_verify_remark,v.kefu_addtime from zjy_user_vip v left join zjy_user u on v.user_id = u.user_id";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$sql .= $where;
		$order = " order by v.kefu_addtime desc";
		$sql .= $order;
		$sql .= " limit {$per_page},$page_size";
		$query = $this->db->query($sql);
		$data['list'] = $query->result_array();
		$sql = "select count(*) as count from zjy_user_vip v left join zjy_user u on v.user_id = u.user_id".$where;
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;

	}
	
	//等待VIP认证的会员
	function vip_no_num($where) {
		$_where = ' where vip_status='.$where;
		$sql = "select count(*) as count from zjy_user_vip v left join zjy_user u on v.user_id = u.user_id";
		$sql .= $_where;
		$query = $this->db->query($sql);
		return $query->row()->count;
	}

	function vip_count_list($parms=array()){
		$tmp = array();

		if(isset($parms['kefu_userid']) && $parms['kefu_userid']){
			$tmp[] = " kefu_userid = '{$parms['kefu_userid']}'";
		}

		if(isset($parms['strtime']) && $parms['strtime']){
			$tmp[] = " kefu_addtime>'{$parms['strtime']}'";
		}

		if(isset($parms['endtime']) && $parms['endtime']){
			$tmp[] = " kefu_addtime<'{$parms['endtime']}'";
		}


		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);

		$sql = "select count(*) as count from zjy_user_vip".$where.' and vip_status=1';
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;
	}

	function invite_list($parms=array(),$data=array()){
        $begin_time = '';
        $end_time = '';
		foreach($parms as $key => $val){
			if($val){
				if($key == 'username'){
					$tmp .= " and p1.{$key} like '%{$val}%'";
				}elseif($key=='invite_username'){
					$invite_userid = $this->get_userid_by_username($val);
					$tmp .= " and p1.invite_userid =".$invite_userid;
				} elseif($key == 'begin_time'){
                    $begin_time = $val;
                } elseif($key == 'end_time'){
                    $end_time = $val;
                }
			}
		}
        $begin_time_tmp = strtotime($begin_time);//转成时间戳格式
        $end_time_tmp = strtotime($end_time);
        if($begin_time != null && $end_time == null) {
            $tmp .= " and p1.add_time >".$begin_time_tmp;
        } elseif($begin_time == null && $end_time != null) {
            $tmp .= " and p1.add_time <".$end_time_tmp;
        } elseif($begin_time != null && $end_time != null) {
            $tmp .= " and p1.add_time<".$end_time_tmp." and p1.add_time>".$begin_time_tmp;
        }

		$where = ' WHERE p3.fstatus=3 AND p3.ftype!=5 AND p1.invite_userid>0 ';
		$tmp && $where = $where.$tmp;

		$order = " GROUP BY p1.user_id order by p1.user_id desc ";
		$sql = 'SELECT SUM(p2.account) as money, count(p2.id) as count,p1.user_id,p1.username,p1.invite_userid,p1.invite_money
				FROM zjy_user AS p1
				LEFT JOIN zjy_borrow_tender AS p2 ON p1.user_id=p2.user_id
				LEFT JOIN zjy_borrow AS p3 ON p2.borrow_id=p3.id'.$where.$order;

		if(isset($data['limit']) && $data['limit'] == 'all'){
			$query = $this->db->query($sql);
			$data['user_list'] = $query->result_array();
			return $data;
		}else{
            if($data['per_page'] && $data['page_size']) {
                $sql .= " limit {$data['per_page']},{$data['page_size']}";
            }
			$query = $this->db->query($sql);
			$data['user_list'] = $query->result_array();
		}

		$query = $this->db->query($sql);
		$result = $query->result_array();

		if($result){
			foreach($result as $v){
				$invite_info = $this->get_by_uid($v['invite_userid']);
				$v['invite_username'] = $invite_info['username'];
				$user_list[] = $v;
			}
		}
		$data['user_list'] = $user_list;

		$sql = "select count(DISTINCT(p1.user_id)) as count FROM zjy_user AS p1
LEFT JOIN zjy_borrow_tender AS p2 ON p1.user_id=p2.user_id
LEFT JOIN zjy_borrow AS p3 ON p2.borrow_id=p3.id
".$where;

		$query = $this->db->query($sql);
		$data['user_count'] = $query->row()->count;

		return $data;
	}

    function get_invite_list($user_id) {
        if($user_id == null) {
            return null;
        }

        $where = ' WHERE p1.invite_userid='.$user_id;

        $sql = 'SELECT SUM(p2.account) as money,p1.user_id,p1.username,p1.invite_userid,p1.invite_money,p1.add_time
				FROM zjy_user AS p1
				LEFT JOIN zjy_borrow_tender AS p2 ON p1.user_id=p2.user_id
				LEFT JOIN zjy_borrow AS p3 ON p2.borrow_id=p3.id'.$where.' Group by p1.user_id';

        $query = $this->db->query($sql);
        $result = $query->result_array();

        //获取邀请人的名字
        $user_list = array();
        if(!empty($result)){
            foreach($result as $v){
                $invite_info = $this->get_by_uid($v['invite_userid']);
                $v['invite_username'] = $invite_info['username'];
                $user_list[] = $v;
            }
            return $user_list;
        } else {
            return null;
        }
    }

	/**
	 * 修改推荐奖励
	 */
	function set_invite_money($user_id, $money = 0){
		$sql = "update zjy_user set invite_money=invite_money+$money, inviteTime = unix_timestamp() where user_id=$user_id";
		$query = $this->db->query($sql);
		return $this->db->affected_rows();
	}
}

